package cn.wd.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wd.dao.GoodsMapper;
import cn.wd.model.Goods;
import cn.wd.model.dto.GoodsDTO;
import cn.wd.service.CustomerService;
import cn.wd.service.ShopBatchService;
import cn.wd.service.GoodsBuyService;
import cn.wd.service.GoodsService;

@Service
public class GoodsServiceImpl implements GoodsService {
	@Autowired
	GoodsBuyService goodsBuyService;
	@Autowired
	CustomerService customerService;
	@Autowired
	ShopBatchService goodsBatchService;
	
	@Autowired
	GoodsMapper goodsMapper;
	@Override
	public void saveGoods(GoodsDTO goodsDTO) throws Exception {
		//1.固化商品批次
		goodsBatchService.insertIfNotExist(goodsDTO.getShopBatch());
		//2.新增或修改商品
		createOrUpdateGoods(goodsDTO);
		//3.新增或者修改客户信息
		customerService.createOrUpdate(goodsDTO);
		//4.新增或者修改客户购买信息
		goodsBuyService.createOrUpdate(goodsDTO);
	}

	private void createOrUpdateGoods(GoodsDTO goodsDTO) {
		Goods queryResult = goodsMapper.queryByGoodsName(goodsDTO.getGoodsName());
		if(queryResult!=null){
			goodsDTO.setGoodsId(queryResult.getGoodsId()+"");
		}
		
		
		Goods goods = new Goods();
		goods.setGoodsName(goodsDTO.getGoodsName());
		goods.setGoodsImgUrl(goodsDTO.getGoodsImgUrl());
		goods.setGoodsBrand(goodsDTO.getGoodsBrand());
		goods.setGoodsUnit(goodsDTO.getGoodsUnit());
		goods.setGoodsCategoryName(goodsDTO.getGoodsCategory());
		if(StringUtils.isNotBlank(goodsDTO.getGoodsId())){
			//修改
			goods.setGoodsId(new Integer(goodsDTO.getGoodsId()));
			goodsMapper.updateByPrimaryKeySelective(goods);
		}else{
			//新增
			goodsDTO.setGoodsId(goodsMapper.insert(goods)+"");
		}
	}

	@Override
	public List<Goods> ajaxLoad(String goodsName) {
		return goodsMapper.selectByGoodsName(goodsName);
	}
}
